package com.xc.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.xc.dto.ResultDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.UUID;

@RestController
@Api(tags = "图片验证码")
public class CodeController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取验证码
     *
     * @return
     */
    @GetMapping("/code")
    @ApiOperation("验证码")
    public ResultDTO getCode() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(130, 45, 4, 100);
        RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdecghigklmzobqrstuvwsyz", 4);  //生成4个随机数
        lineCaptcha.setGenerator(randomGenerator);
        lineCaptcha.createCode();
        String code = lineCaptcha.getCode();  //获取验证码
        UUID uuid = UUID.randomUUID();
//        缓存一分钟的验证码
        redisTemplate.opsForValue().set("code:" + uuid, code, Duration.ofMinutes(1));
        return ResultDTO.builder()
                .msg("code:" + uuid)
                .data("data:image/png;base64," + lineCaptcha.getImageBase64().toString())
                .build();
    }
}
